package xyz.scootaloo.mono.base.service.async

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import java.util.concurrent.ExecutorService
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

/**
 * @author flutterdash@qq.com
 * @since 2021/9/8 23:09
 */
@Component
open class AsyncTaskService {

    /**
     * 单线程任务调度
     *
     * 提交的任务会被立刻调度到单线程线程池排队执行
     *
     * @param block 需要异步执行的任务
     */
    fun logging(block: () -> Unit) = singleTaskScheduler.execute(block)

    /**
     * 指定延迟后执行任务
     *
     * @param second 延迟时间, 单位: 秒
     * @param block  需要执行的任务
     */
    fun delay(second: Long, block: () -> Unit) {
        mutableTaskScheduler.schedule(block, second, TimeUnit.SECONDS)
    }

    fun schedule(block: () -> Unit) {
        delay(0, block)
    }

    /**
     * 执行带有回调的任务
     *
     * @param task 任务的定义, 可以在这个对象中指定任务的回调
     * @param second, 延迟[second]秒后执行任务, 默认立刻执行
     */
    fun <T> taskWithCallback(task: TaskDefinition<T>, second: Long = 0) {
        task.scheduler = this.mutableTaskScheduler
        delay(second, task.buildRunnable())
    }

    @Autowired
    @Qualifier("monoMutableTaskScheduler")
    private lateinit var mutableTaskScheduler: ScheduledExecutorService

    @Autowired
    @Qualifier("monoSingleTaskScheduler")
    private lateinit var singleTaskScheduler: ExecutorService
}
